package com.chenyi.data.structure.queue;

/**
 * @author by chenyi
 * @className LinkedQueue
 * @date 2021/12/26 14:21
 */

public class LinkedQueue implements Queue{

    /**
     * 队列头
     */
    private Node front;

    /**
     * 队列尾
     */
    private Node rear;

    /**
     * 最大个数
     */
    private int maxSize;

    /**
     * 队列有效个数
     */
    private int size;

    public LinkedQueue(int maxSize) {
        this.maxSize = maxSize;
    }

    @Override
    public boolean addQueue(int e) {
        if (isFull()) {
            System.out.println("队列已满无法添加数据");
            return false;
        }
        // 判断是否是第一次添加
        if (front == null) {
            front = new Node(e, null);
            rear = front;
        } else {
            rear.next = new Node(e, null);
            rear = rear.next;
        }
        size++;
        return true;
    }

    @Override
    public boolean isFull() {
        return maxSize == size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        Node f = front;
        front = f.next;
        size--;
        return f.element;
    }

    @Override
    public void showQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        Node f = front;
        for (int i = 0; i < size; i++) {
            System.out.printf("queue[%d]=%d\n", i, f.element);
            f = f.next;
        }

    }

    @Override
    public int peekHeadQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return front.element;
    }

    private static class Node {
        private Integer element;
        private Node next;

        public Node(Integer element, Node next) {
            this.element = element;
            this.next = next;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "element=" + element +
                    '}';
        }
    }
}
